package com.my.socket.pipe;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * Created by ZhongGang
 * at 2018/6/29 9:50
 */
public class PipeStream {
    private static final Logger LOGGER = LoggerFactory.getLogger(PipeStream.class);

    public static void main(String[] args) throws Exception {
        PipedInputStream pipedInputStream = new PipedInputStream();
        PipedOutputStream pipedOutputStream = new PipedOutputStream();
        pipedOutputStream.connect(pipedInputStream);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    LOGGER.info("waiting for reading...");
                    int read = pipedInputStream.read();
                    while (read != -1) {
                        LOGGER.info("read: {}", (char) read);
                        read = pipedInputStream.read();
                    }
                } catch (Exception e) {
                    LOGGER.error("exception caugth, the error is {}", e.getMessage());
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    pipedOutputStream.write("I am Alex Zhong".getBytes());
                    pipedOutputStream.close();
                } catch (Exception e) {
                    LOGGER.error("exception caugth, the error is {}", e.getMessage());
                }
            }
        }).start();

        while (true) {

        }
    }
}
